﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.ComponentModel.DataAnnotations;
using VehicleMaintenance.Comm;
using VehicleMaintenance.Events;

namespace VehicleMaintenance.UserControls
{
	public partial class ucFormInput : UserControl
	{

		#region 私有变量及属性

		/// <summary>
		/// 当前处理数据类型，对应数据库表
		/// </summary>
		private Type type;

		#endregion 私有变量及属性

		#region 构造函数

		public ucFormInput()
		{
			InitializeComponent();
		}

		public ucFormInput(Type t)
		{
			InitializeComponent();

			type = t;

			CreatControls(type, tabPanel);
		}

		#endregion 构造函数

		#region 私有方法

		/// <summary>
		/// 清空当前窗体的所有数据
		/// </summary>
		/// <param name="con"></param>
		private void ClearData(Control con)
		{
			foreach (Control item in con.Controls)
			{
				if (item is TextBox)
				{
					((TextBox)item).Clear();
				}
				else if (item is ComboBox)
				{
					((ComboBox)item).SelectedIndex = 0;
				}
				ClearData(item);
			}
		}

		private void CreatControls(Type t, TableLayoutPanel tabPanel)
		{
			tabPanel.Controls.Clear();

			foreach (System.Reflection.PropertyInfo p in t.GetProperties())
			{
				var a = p.GetCustomAttributes(typeof(DisplayAttribute), true);
				if (a.Count() > 0)
				{
					DisplayAttribute display = a.Single() as DisplayAttribute;

					Label lb = new Label();
					lb.Anchor = AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Top;
					lb.TextAlign = ContentAlignment.MiddleRight;
					lb.Text = display.Name;
					tabPanel.Controls.Add(lb);

					Control con = new Control();
					var b = p.GetCustomAttributes(typeof(ControlTypeAttribute), true);
					if (b.Count() > 0)
					{
						ControlTypeAttribute controlType = b.Single() as ControlTypeAttribute;
						switch (controlType.Type)
						{
							case "ComboBox":
								{
									ComboBox cbox = new ComboBox();
									cbox.Anchor = AnchorStyles.Bottom | AnchorStyles.Left  | AnchorStyles.Top;
									cbox.Items.AddRange(controlType.Values);
									cbox.DropDownStyle = ComboBoxStyle.DropDownList;
                                    if (cbox.Items.Count > 0)
                                    {
                                        cbox.SelectedIndex = 0;
                                    }
									con = cbox;
									break;
								}
                            case "DateTimePicker":
                                {
                                    DateTimePicker picker = new DateTimePicker();
                                    picker.Anchor = AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Top;
									picker.Format = DateTimePickerFormat.Custom;
									picker.CustomFormat = "yyyy年MM月dd日";
                                    con = picker;
                                    break;
                                }
							default: break;
						}
					}
					else
					{
						TextBox txt = new TextBox();
						txt.Anchor = AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Top;
						con = txt; 
					}

                    con.Name = p.Name;
					con.Margin = new Padding(0, 0, 20, 0);
					tabPanel.Controls.Add(con);

					#region old
					//if (p.Name.EndsWith("ID",true,null))
					//{
					//    Button btn = new Button();
					//    btn.Top = txt.Top + tabPanel.Top;
					//    btn.Left = txt.Left + txt.Width - btn.Width + tabPanel.Left;
					//    form.cre
					//    form.Controls.Add(btn);
					//}

					//var attribute = typeof(ModelClass).GetProperties()
					//      .Where(p => p.Name == "Description")
					//      .Single()
					//      .GetCustomAttributes(typeof(StringLengthAttribute), true)
					//      .Single() as StringLengthAttribute;

					//Console.WriteLine("Maximum Length: {0}", attribute.MaximumLength); 
					#endregion old

					//必填项
					var r = p.GetCustomAttributes(typeof(RequiredAttribute), true);
					if (r.Count() > 0)
					{
						con.BackColor = Color.LightYellow;
					}

					//弹窗选择
					if (p.PropertyType.Name.ToLower().Equals("int32"))
					{
						if (p.Name.EndsWith("ID", true, null))
						{
							con.KeyPress += new KeyPressEventHandler(KeyEvents.DisabledInput_KeyPress);
							con.KeyDown += new KeyEventHandler(KeyEvents.DisabledInput_KeyDown);
							con.BackColor = Color.LightGray;
						}
					}					
				}
			}
		}

		#endregion 私有方法

		#region 公开方法

		public void InitializeControls(Type t)
		{
			type = t;

			CreatControls(type, tabPanel);
		}

		public Control GetControlByName(string strName)
		{
			return tabPanel.Controls[strName];
		}

		/// <summary>
		/// 清空当前窗体的所有数据
		/// </summary>
		/// <param name="con"></param>
		public void ClearData()
		{
			ClearData(tabPanel);
		}

		public bool VerifyInput()
		{
			errorProvider1.Clear();
			foreach (Control con in tabPanel.Controls)
			{
				if (con.Text.Equals(""))
				{
					var attributes = type.GetProperties()
									  .Where(p => p.Name == con.Name)
									  .Single()
									  .GetCustomAttributes(typeof(RequiredAttribute), true);
					if (attributes.Length > 0)
					{
						var attribute = attributes.Single() as RequiredAttribute;
						if (attribute != null)
						{
							errorProvider1.SetError(con, attribute.ErrorMessage);
							con.Focus();
							return false;
						}
					}
				}
			}

			return true;
		}

		public void SetValues(object obj)
		{
			if (obj != null)
			{
				foreach (System.Reflection.PropertyInfo p in type.GetProperties())
				{
					Control con = GetControlByName(p.Name);
					if (con != null)
					{
						if (p.GetValue(obj, null) != null)
						{
							switch (p.PropertyType.Name.ToLower())
							{
								case "int32":
									{
										if (p.Name.EndsWith("ID", true, null))
										{
											GetControlByName(p.Name).Tag = p.GetValue(obj, null).ToString();
										}
										else
										{
											GetControlByName(p.Name).Text = p.GetValue(obj, null).ToString();
										}
										break;
									}
								default:
									{
										GetControlByName(p.Name).Text = p.GetValue(obj, null).ToString();
										break;
									}
							}
						}

					}
				}
			}
		}

		public void GetValues(object obj)
		{
			if (obj != null)
			{
				foreach (System.Reflection.PropertyInfo p in type.GetProperties())
				{
					Control con = GetControlByName(p.Name);
					if (con != null)
					{
						string value = GetControlByName(p.Name).Text;
						if (!string.IsNullOrEmpty(value))
						{
							object val = value;
							switch (p.PropertyType.Name.ToLower())
							{
								case "int32":
									{
										//var attribute = p.GetCustomAttributes(typeof(ForeignKeyAttribute), true);
										//if (attribute.Count() > 0)
										if (p.Name.EndsWith("ID", true, null))
										{
											object tag = GetControlByName(p.Name).Tag;
											if (tag != null)
											{
												val = Convert.ToInt32(tag);
											}
											else
											{
												val = 0;
											}
										}
										else
										{
											val = Convert.ToInt32(val);
										}
										break;
									}
								case "decimal": val = Convert.ToDecimal(val); break;
								default: break;
							}
							p.SetValue(obj, val, null);
						}
					}
				}
			}
		}

		#endregion 公开方法
	}
}
